package com.example.animationmodule.pathmeasure

import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.android.baselibrary.utils.dp2px

/**
 * @author: Mr.You
 * @create: 2023-12-01 13:09
 * @description: 画圆圈
 **/
class GetSegmentView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defaultStyle: Int = 0) :
    View(context, attributeSet, defaultStyle) {
    private var mPaint: Paint
    private var mDstPath :Path
    private var mCirclePath:Path
    private var mPathMeasure :PathMeasure
    private var mCurAnimValue = 0.0f
    init {
        setLayerType(LAYER_TYPE_SOFTWARE,null)
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = dp2px(4).toFloat()
        mPaint.color = Color.BLUE


        mDstPath = Path()
        mCirclePath = Path()
        mCirclePath.addCircle(200f, 200f, dp2px(50).toFloat(),Path.Direction.CW)

        mPathMeasure = PathMeasure(mCirclePath,true)

        val animator = ValueAnimator.ofFloat(0f, 1.0f)
        animator.addUpdateListener {
            mCurAnimValue = it.animatedValue as Float
            invalidate()
        }
        animator.duration = 2000
        animator.repeatCount =ValueAnimator.INFINITE
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.translate(100f,100f)
        val length =  mPathMeasure.length
        Log.i("TAG111", "onDraw: length $length")
        val stop = length * mCurAnimValue
        val start = (stop -((0.5-Math.abs(mCurAnimValue-0.5))*length))
        //根据路径长度截取对应的路径线段
        mDstPath.reset()
        canvas.drawColor(Color.WHITE)
        mPathMeasure.getSegment(start.toFloat(),stop,mDstPath,true)
        canvas.drawPath(mDstPath,mPaint)
    }
}